<template>
  <div class="padding-16">
    <a-card class="general-card" title="创建文章">
      <template #extra>
        <a-button type="secondary">草稿箱</a-button>
        <a-button class="ml-16" type="primary" @click="handlePush">发布</a-button>
      </template>
      <div class="flex-item">
        <a-input v-model="formState.title" class="fs-18" placeholder="输入文章标题..."></a-input>
      </div>
      <div class="mt-16">
        <Editor v-model="formState.content" :min-height="500" />
      </div>
    </a-card>
    <!--  发布文章  -->
    <a-drawer
      v-model:visible="dialogVisible"
      title="确认发布"
      width="320px"
      :footer="false"
    >
        <a-form
          ref="formRef"
          :model="formState"
          :rules="formRules"
          auto-label-width
          @submit="handleSubmit"
        >
          <a-form-item label="文章分类" name="category_id">
            <a-tree-select
              v-model="formState.category_id"
              node-key="id"
              :field-names="fieldNames"
              :data="categoryOptions"
              placeholder="请选择文章分类"
            />
          </a-form-item>
          <a-form-item label="封面图片" nam="cover">
            <a-input v-model="formState.cover" autocomplete="off"></a-input>
          </a-form-item>
          <a-form-item label="可见性" nam="visible">
            <a-radio-group v-model="formState.visible">
              <a-radio :value="1">显示</a-radio>
              <a-radio :value="0">隐藏</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="排序" nam="sort">
            <a-input-number v-model="formState.sort" :min="1" :max="9999" />
          </a-form-item>
          <a-form-item label="阅读数量" nam="views">
            <a-input-number v-model="formState.views" :min="1" :max="9999" />
          </a-form-item>
          <div class="form-footer">
            <a-button key="submit" html-type="submit" type="primary" :loading="loading">确 定</a-button>
            <a-button class="ml-16" @click="handleCancel">取消</a-button>
          </div>
        </a-form>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import Editor from "@/components/editor/index.vue";
import { Message } from "@arco-design/web-vue";
import { articleCreate, articleUpdate, articleDetail, categoryTreeList } from "@/api/content/article.ts";
import get from "lodash/get";
import useLoading from "@/hooks/loading.ts";

const route = useRoute();
const router = useRouter();

const { loading, setLoading } = useLoading(true);
const dialogVisible = ref(false);

const formRef = ref();
const formState = reactive({
  id: undefined,
  title: undefined,
  content: undefined,
  category_id: undefined, // 分类
  cover: undefined, // 封面
  views: 400, // 展示数量
  visible: 1, // 是否可见
  sort: 100 // 排序
});

const formRules = reactive({
  category_id: [{ required: true, message: "文章分类不能为空", trigger: "blur" }],
  visible: [{ required: true, message: "可见状态不能为空", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
});

function handlePush() {
  console.log(formState);
  if (!formState.title || !formState.content) {
    Message.warning("标题、内容不能为空");
  } else {
    dialogVisible.value = true;
  }
}

function handleCancel() {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  formState.id = undefined;
  formState.title = undefined;
  formState.content = undefined;
  formState.category_id = undefined;  // 分类
  formState.cover = undefined;  // 封面
  formState.views = 400;  // 展示数量
  formState.visible = 1;  // 是否可见
  formState.sort = 100;  // 排序
}

const handleSubmit = async ({ values, errors }) => {
  console.log("values:", values, "\nerrors:", errors);
  setLoading(true);
  try {
    const params = {
      ...formState
    };

    if (params.id) {
      await articleUpdate(params);
    } else {
      await articleCreate(params);
    }

    handleCancel();
    Message.success("保存成功！");
    router.replace({ path: "/article/list" });
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

// 获取文章内容
const getDetails = async (articleId: number) => {
  setLoading(true);
  try {
    const { data } = await articleDetail({
      id: articleId
    });

    Object.keys(formState).forEach((key) => {
      // @ts-ignore
      formState[key] = data[key];
    });
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

// 分类多级菜单选择
const categoryOptions = ref([]);

const fieldNames = {
  label: "name",
  value: "id",
  children: "children"
};

async function fetchCategoryTree() {
  setLoading(true);
  try {
    const { data } = await categoryTreeList();
    categoryOptions.value = [{ name: "顶级分类", id: 0 }].concat(get(data, "list", []) || []);
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchCategoryTree();
  if (route.query.id) {
    getDetails(route.query.id);
  }
});
</script>

<style scoped lang="less">
.operate {
  margin-left: 8px;
}

.status {
  margin-left: 24px;
  color: #8c939d;
  font-size: 12px;
}
</style>
